package cn.hhz._05weibo.common.exception;

import cn.hhz._05weibo.common.response.JsonResult;
import cn.hhz._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler
    public JsonResult doHandlerIllegalArg(IllegalArgumentException exception){
        log.error(exception.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,exception.getMessage());
    }

//    @ExceptionHandler
//    public JsonResult doHandlerRuntime(Exception ex){
//        return new JsonResult(StatusCode.OPERATION_FAILED,ex.getMessage());
//    }
//DTO方式处理异常
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error(ex.getFieldError().getDefaultMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getFieldError().getDefaultMessage());
    }
//参数方式处理异常
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        log.error(ex.getMessage().split(":")[1].trim());
        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getMessage().split(":")[1].trim());
    }
//    @ExceptionHandler
//    public JsonResult dHandleThrowable(Throwable ex){
//        log.error(ex.getMessage());
//        return new JsonResult(StatusCode.THROWABLE_ERROR,ex.getMessage());
//    }
}
